"""
@author: Shizuku
@file: 2022-11-16-practice.py
@time: 2022/11/16 15:06
"""
import re
import random
import datetime


def exer1():
    alp = input("请输入一段字符：")
    print(alp.title())


def exer2():
    alp = input("请输入一段字符：")
    if re.match(r'^[abc].*[xyz]$', alp, flags=0):
        print("符合")
    else:
        print("不符合")


def exer3():
    lst = []
    for i in range(0, 5):
        lst.append(random.randint(1, 100))
    lst.sort()
    print(lst, sum(lst))


def exer4():
    lst1 = ['a', 'b', 'c']
    lst2 = ['d', 'e', 'f']
    for i in lst2:
        lst1.append(i)
    print(lst1, lst2)


def exer5():
    num = int(input("请输入一个大于2的数:"))
    if num >= 2:
        if isprimenum(num):
            print("是素数")
        else:
            print("不是素数")
    else:
        print("请输入正确的数")


def isprimenum(num):
    for i in range(2, num-1):
        if num % i == 0:
            return False
    return True


def exer6():
    while True:
        choice = input("请输入百分以内的分数:")
        if choice == 'q':
            break
        if choice.isdigit():
            score = int(choice)
            if 1 <= score < 60:
                print("不及格")
            elif 60 <= score < 80:
                print("C")
            elif 80 <= score < 90:
                print("B")
            elif 90 <= score <= 100:
                print("A")
            else:
                print("请输入正确的分数")
        else:
            print("请输入正确的分数")


def exer7():
    music = {"华语女歌手": {"邓紫棋": ["泡沫", "光年之外"], "张韶涵": ["阿娇"]},
             "华语男歌手": {"陈奕迅": ["十年", "红玫瑰"], "林俊杰": ["曹操"]}
             }
    print("界面菜单:\n", "1.华语女歌手\n", "2.华语男歌手")
    while True:
        choice = input("请输入您的选择:")
        if choice == '1':
            for key in music["华语女歌手"]:
                print(key)
            singer = input("请选择歌手:")
            if singer == "邓紫棋":
                print(music["华语女歌手"]["邓紫棋"])
                song = input("请选择要播放的歌曲:")
                print(song)
            elif singer == "张韶涵":
                print(music["华语女歌手"]["张韶涵"])
                song = input("请选择要播放的歌曲:")
                print(song)
            else:
                print("没有这位歌手,请重新选择")
        elif choice == '2':
            for key in music["华语男歌手"]:
                print(key)
            singer = input("请选择歌手:")
            if singer == "陈奕迅":
                print(music["华语男歌手"]["陈奕迅"])
                song = input("请选择要播放的歌曲:")
                print(song)
            elif singer == "林俊杰":
                print(music["华语男歌手"]["林俊杰"])
                song = input("请选择要播放的歌曲:")
                print(song)
            else:
                print("没有这位歌手,请重新选择")
        elif choice == 'q':
            break
        else:
            print("请输入正确的格式")


def exer8():
    from datetime import datetime
    time_str = '30/06/2022 10-30'
    dt_time = datetime.strptime(time_str, "%d/%m/%Y %H-%M")
    time_str1 = dt_time.strftime('%Y-%m-%d %H:%M')
    print(time_str1)


def exer9():
    year = int(input("请输入年份："))
    month = int(input("请输入月份："))
    day = int(input("请输入日："))
    result = datetime.datetime(year, month, day)
    print(result.strftime("%j"))


def exer10():
    alp = []
    dig = []
    other = []
    strs = input("请输入一段字符：")
    for i in strs:
        if i.isdigit():
            dig.append(i)
        elif 'a' <= i <= 'z' or 'A' <= i <= 'Z':
            alp.append(i)
        else:
            other.append(i)
    print("字母的个数是：", len(alp))
    print("数字的个数是：", len(dig))
    print("其他字符的个数是：", len(other))


def scstore():
    goods = {'F00001': {'name': '苹果', 'price': '1.2'},
             'F00002': {'name': '香蕉', 'price': '2.2'},
             'F00003': {'name': '梨子', 'price': '3.2'}}
    wd = "欢迎进入三创购物系统"
    print(wd.center(50, "*"))
    option = input('请选择选项：\n1、登录\n2、注册\n')
    with open('userInfo.txt', 'r+') as f:
        user = {}
        for i in f.readlines():
            user = dict(user, **eval(i))
    if option == "1":
        login(user)
        print("以下是商品列表：\n", goods)
        restart = True
        while restart:
            restart = False
            choice = input('请选择选项：\n1、加入购物车\n2、查看购物车\n3、结账\n')
            if choice == '1':
                addtoshoppingcar(goods)
                restart = True
            elif choice == '2':
                shoppingcar()
                restart = True
            elif choice == '3':
                checkout(user)
                restart = True
            elif choice == 'exit':
                print("退出")

    elif option == "2":
         register(user)
    elif option == "exit":
         print("退出")
    else:
        print("请输入正确的选项！")


def login(user):
    restart = True
    while restart:
        restart = False
        global username
        username = input("请输入用户名：")
        passwd = input("请输入密码：")
        if username in user.keys() and passwd == user[username]['passwd']:
            print("登陆成功\n")
        else:
            restart = True
            print("用户名或密码错误，请重新输入")


def register(user):
        restart = True
        while restart:
            restart = False
            rusername = input("请输入用户名：")
            rpasswd = input("请输入密码：")
            if rusername in user.keys():
                restart = True
                print("该用户名已被占用，换个名字试试吧")
            else:
                print("注册成功，新用户获得￥100")
                newuser = {rusername: {'passwd': rpasswd, 'money': '100'}}
                with open('userInfo.txt', 'a') as f:
                    f.write(str(newuser) + '\n')


def addtoshoppingcar(goods):
    code = input("请输入商品编号：")
    if code in goods.keys():
        qty = input("请输入购买数量：")
        with open(username + "shoppingcar.txt", 'a',
                  encoding='utf-8') as f:
            buy = goods[code]['name']
            total = int(qty) * float(goods[code]['price'])
            total = round(total, 2)
            f.writelines(buy + ' ' + qty + ' ' + str(total) + '\n')
    else:
        print("不存在该商品")

def shoppingcar():
    with open(username + "shoppingcar.txt", 'r+',
              encoding='utf-8') as f:
        item = []
        for i in f.readlines():
            item.append(i.strip())
        print(item)

def checkout(user):
    with open(username + "shoppingcar.txt", 'r+',
              encoding='utf-8') as f:
        item = []
        expense = 0
        for i in f.readlines():
            item.append(i.strip())
        for i in list(item):
            expense = expense + float(i.split()[2])
        if expense > float(user[username]['money']):
            print("余额不足，请充值")
        else:
            money = float(user[username]['money']) - expense
            print("本此消费", expense, "元，剩余", money, "元，欢迎下次光临！")
            with open(username + "shoppingcar.txt", 'w',
                      encoding='utf-8') as f:
                f.write('')
            user[username]['money'] = money
            with open('userInfo.txt', 'w', encoding='utf-8') as f:
                f.write('')
            with open('userInfo.txt', 'a', encoding='utf-8') as f:
                for i in list(user.items()):
                    qwe = {}
                    qwe[i[0]] = i[1]
                    f.write(str(qwe) + '\n')

scstore()
